package com.jee.ssm.common.socket.guideScreen;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

public class SocketServer extends Thread {
	
	private Logger logger = Logger.getLogger(SocketServer.class);

    private static Integer port = 5000;
    private static boolean started = false;
    private static ServerSocket ss = null;

    public static Map<String, SocketHandle> socketMap = Collections.synchronizedMap(new HashMap<>());
    private static ExecutorService threadPool = Executors.newCachedThreadPool();

    @Override
    public void run() {
        try {
            ss = new ServerSocket(port);
            started = true;
            logger.info("端口已开启,占用" + port + "端口号....");
        } catch (BindException e) {
            logger.info("端口使用中....");
            logger.info("请关掉相关程序并重新运行服务器！");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            while (started) {
                Thread.sleep(1);
                Socket s = ss.accept();
                logger.info("a client connected!");
                threadPool.execute(new Thread(new SocketHandle(s)));
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("socket服务异常");
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.info("延迟异常");
        } finally {
            logger.info("连接异常，关闭socket服务");
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
